#ifndef MESSAGE_H
#define MESSAGE_H

#include <boost\lexical_cast.hpp>
#include "int32_from_hex.h"

namespace comunication {

	class message
	{
	public:
		enum { header_length = 4};
		enum { message_id = header_length - 1 };
		
		message(): id_(0), size_(0), body_data(nullptr)
		{
			memset(header_data, 0, header_length);
		}

		void clear()
		{
			memset(header_data, 0, message::header_length);
			erase_body_data();
		}

		char* get_header_data()
		{
			return header_data;
		}

		char* get_body_data()
		{
			return body_data;
		}

		int get_id() const
		{
			return id_;
		}

		int get_size() const 
		{
			return size_;
		}

		bool decode_header()
		{
			bool result = false;
			try 
			{
				id_ = boost::lexical_cast<conversion::int32_from_hex>(header_data[0]);

				char size_raw[header_length] = "";
				std::memcpy(size_raw, &header_data[1], header_length - 1);
				size_ = boost::lexical_cast<conversion::int32_from_hex>(size_raw);

				erase_body_data();
				body_data = new char[size_];
				memset(body_data, 0, size_);
				result = true;
			} 
			catch(boost::bad_lexical_cast& e)
			{
				std::cout<<e.what()<<std::endl;
			}
			return result;
		}

	private:
		void erase_body_data()
		{
			if (body_data != nullptr) 
			{
				delete[] body_data;
				body_data = nullptr;

			}
		}
		int id_;
		int size_;
		char header_data[header_length];
		char* body_data;
	};
}
#endif